package qe.spider.tools;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.UnicodeUtil;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import qe.spider.MainSelect;
import qe.spider.cfg.Factor;
import qe.spider.cfg.PlateConfig;
import qe.spider.cfg.TradeConfig;
import qe.spider.cfg.TradeHuaXinCfg;
import qe.spider.vo.GoodStock;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Slf4j
public class SyncFactor {
    private final String webHook = "http://" + System.getProperty("wsn_ip", "47.99.196.159") + ":" + System.getProperty("wsn_port", "8888") + "/gs/factor/";
//    private final String webHook = "http://127.0.0.1:8000/gs/factor/";

    public static void main(String[] args) throws IOException, InterruptedException {
        Factor ts = new SyncFactor().get();
        TradeHuaXinCfg xw = TradeHuaXinCfg.builder().userName("谢炜华鑫模拟账号").userId("00646531").password("63304162").maxBuyCntPerDay(20).buyStrategy("shangbang_buy").sellStrategy("fall_avg_sell").build();
        TradeHuaXinCfg xf = TradeHuaXinCfg.builder().userName("徐樊华鑫模拟账号").userId("00361630").password("95094485").maxBuyCntPerDay(10).buyStrategy("zhangting_buy").sellStrategy("fall_avg_sell").build();
        ts.getOthers().setTradeConfig(TradeConfig.builder().maxBuyCntPerDay(10).tradeHuaXinCfgList(List.of(xw, xf)).build());
//        ts.getOthers().getTradeConfig().getTradeHuaXinCfgList().addAll(List.of(xw, xf));
        ts.getOthers().setPlateConfig(PlateConfig.builder().excludesTHSGaiNian(List.of("融资融券", "深股通")).build());
        System.out.println(new Gson().toJson(ts.getOthers()));
        Thread.sleep(1000);
    }

    public Factor get() {
        OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder().url(webHook).header("Content-Type", "application/json").build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) return MainSelect.factor = loadFactor();
            String result = UnicodeUtil.toString(response.body().string());
            Factor ts = new Gson().fromJson(result, Factor.class);
            return MainSelect.factor = ts;
        } catch (IOException e) {
            log.error("WebSocket msg send error： ", e);
        }
        return MainSelect.factor = loadFactor();
    }

    public Factor loadFactor() {
        String json = FileUtil.readString("factors/CurrentFactor.json", "UTF-8");
        Factor ts = new Gson().fromJson(json, Factor.class);
        log.debug(ts.toString());
        return ts;
    }
}
